﻿using System;
using System.Linq;
using System.Threading;

namespace thread_sync
{
    class Food {
        private int food_count_ = 20;
        public bool getFood() {
            Thread.Sleep(500);
            System.Console.WriteLine("Food remain {0}",food_count_);
            if (food_count_ > 0) {
                food_count_--;
                return true;
            }else{
                return false;
            }
        }
    }
    class Cat
    {
        private Food food_;
        public Cat(Food food) { food_ = food; }
        public void work()
        {
            while (true)
            {
                bool food_flag = false;
                lock (food_) { food_flag = food_.getFood(); }
                if (!food_flag) break; 

                System.Console.WriteLine("{0} > miaomiao", DateTime.Now.ToString());
            }
        }
    }

    class Doggy
    {
        private Food food_;
        public Doggy(Food food) { food_ = food; }
        public void work()
        {
            while (true)
            {
                bool food_flag = false;
                lock (food_) { food_flag = food_.getFood(); }
                if (!food_flag) break;

                System.Console.WriteLine("{0} > wangwang", DateTime.Now.ToString());
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Food food = new Food();
            Cat cat = new Cat(food);
            Doggy doggy = new Doggy(food);
            // 创建两个前台线程，对临界资源进行同步访问。
            Thread cat_thread = new Thread(cat.work);
            Thread doggy_thread = new Thread(doggy.work);
            cat_thread.Start();
            doggy_thread.Start();

            cat_thread.Join();
            doggy_thread.Join();
        }
    }
}
